package com.ivy.dao.impl;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.ivy.dao.UserDao;
import com.ivy.entity.User;
import com.ivy.utils.JdbcUtils;

public class UserDaoImpl implements UserDao{

	@Override
	public void insert(User user) {
		String sql = "insert into user(telephone,username,password) values(?,?,?);";
		QueryRunner qr = JdbcUtils.getQueryRunner();
		
		try {
			qr.update(sql,user.getTelephone(),user.getUsername(),user.getPassword());
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	@Override
	public User findUserByTelephone(String telephone) {
		String sql = "select * from user where telephone = "+telephone+";";
		User user = null;
		try {
			QueryRunner qr = JdbcUtils.getQueryRunner();
			user = qr.query(sql, new BeanHandler<User>(User.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return user;
	
	}

	@Override
	public User findUser(User u) {
		//select * from user where username = 'ivy' and password = '123' ;
		String sql = "select * from user where telephone = '"+ u.getTelephone() +"' and password = '"+ u.getPassword()+"' ;";
		User user = null;
		try {
			QueryRunner qr = JdbcUtils.getQueryRunner();
			user = qr.query(sql, new BeanHandler<User>(User.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return user;
	}

}
